<template>

  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <span class="cardHeader">{{ apartmentForm.id ? "修改公寓" : "添加公寓" }}</span>
    </template>
    <AreaSelector></AreaSelector>

    <el-form label-width="120px" style="width: 70%;">
      <el-form-item label="公寓名称">
        <el-input v-model="apartmentForm.name"></el-input>
      </el-form-item>

      <el-form-item label="公寓介绍">
        <el-input type="textarea" v-model="apartmentForm.introduction"></el-input>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input placeholder="请输入详细地址" v-model="apartmentForm.addressDetail"></el-input>
      </el-form-item>
      <el-form-item label="公寓前台电话">
        <el-input placeholder="请输入详细地址" v-model="apartmentForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="是否发布">
        <el-radio-group v-model="apartmentForm.isRelease">
          <el-radio :label="0">未发布</el-radio>
          <el-radio :label="1">已发布</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="公寓配套">
        <el-select v-model="apartmentForm.facilityInfoIds" style="width: 100%;" multiple clearable
          placeholder="请选择公寓配套">
          <el-option :label="facilityInfo.name" :value="facilityInfo.id"
            v-for="(facilityInfo) in facilityInfoList" :key="facilityInfo.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="公寓标签">
        <el-select v-model="apartmentForm.labelIds" style="width: 100%;" multiple clearable @change=""
          placeholder="请选择公寓标签">
          <el-option :value="item.id" :label="item.name" v-for="item in labelInfoList" :key="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="公寓图片">
        <el-upload v-model:file-list="apartmentForm.graphVoList" action="/admin/file/upload" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess"
          :headers="{ ACCESS_TOKEN: userInfoStore.token }">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>

    <div class="btnGroup">
      <el-button style="width: 150px;" @click="cancel">取消</el-button>
      <el-button style="width: 150px;" type="primary" @click="saveOrUpdate">确认</el-button>
    </div>
  </el-card>

</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import apartmentApi, { ApartmentData, FacilityInfoData, LabelInfoData } from '@/api/apartment'
import { useRoute, useRouter } from 'vue-router'
import { useUserInfoStore } from '@/store/modules/model/userInfoModel'
import { useAreaSelectorStore } from '@/store/modules/model/areaSelectorModel'
import { storeToRefs } from 'pinia'
let areaSelectorStore = useAreaSelectorStore()
let {provinceId, provinceName, cityId, cityName, districtId, districtName} = storeToRefs(areaSelectorStore)
let userInfoStore = useUserInfoStore()
let route = useRoute()
let router = useRouter()
const apartmentForm = ref<ApartmentData>({
  name: '',
  introduction: '',
  districtId: '',
  districtName: '',
  cityId: '',
  cityName: '',
  provinceId: '',
  provinceName: '',
  addressDetail: '',
  phone: '',
  isRelease: '',
  // 	公寓配套id
  facilityInfoIds: [],
  // 	公寓配套信息
  facilityInfoList: [],
  // 	公寓标签id
  labelIds: [],
  // 公寓标签信息
  labelInfoList: [],
  // 图片信息
  graphVoList: []
})

let facilityInfoList = ref<FacilityInfoData[]>([])
let labelInfoList = ref<LabelInfoData[]>([])
//获取公寓的配套信息
let getFacilityInfoList = async ()=>{
  let {data} = await apartmentApi.getFacilityInfoList();
  facilityInfoList.value = data;
}
//获取公寓的标签信息
let getLabelInfoList = async ()=>{
  let {data} = await apartmentApi.getLabelInfoList();
  labelInfoList.value = data;
}
//在修改功能中根据id查询公寓信息
let getApartmentById = async (apartmentId : number | string)=>{
  let {data} = await apartmentApi.getApartmentById(apartmentId);
  apartmentForm.value = data;
  apartmentForm.value.facilityInfoIds = apartmentForm.value.facilityInfoList?.map(item=>{
    return item.id as number;
  })
  apartmentForm.value.labelIds = apartmentForm.value.labelInfoList?.map(item=>item.id as number);
  console.log(apartmentForm.value);
}
//在页面初始化时，获取公寓的配套和标签，以及在修改功能中根据id获取公寓信息进行回显
onMounted(()=>{
  getFacilityInfoList()
  getLabelInfoList()
  if(route.query.apartmentId){
    //表示修改功能
    getApartmentById(route.query.apartmentId as string)
  }
})

//保存或修改公寓信息的函数
let saveOrUpdate = async ()=>{
  apartmentForm.value.provinceId = provinceId.value
  apartmentForm.value.provinceName = provinceName.value
  apartmentForm.value.cityId = cityId.value
  apartmentForm.value.cityName = cityName.value
  apartmentForm.value.districtId = districtId.value
  apartmentForm.value.districtName = districtName.value
  await apartmentApi.saveOrUpdateApartment(apartmentForm.value);
  ElMessage.success("保存成功")
  router.push("/apartmentManagement/apartmentManagement/apartmentManagement")
}

//取消操作
let cancel = ()=>{
  router.push("/apartmentManagement/apartmentManagement/apartmentManagement")
}

const fileList = ref<UploadUserFile[]>([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'plant-1.png',
    url: '/images/plant-1.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'plant-2.png',
    url: '/images/plant-2.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'figure-1.png',
    url: '/images/figure-1.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'figure-2.png',
    url: '/images/figure-2.png',
  },
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.cardHeader {
  font-size: 18px;
  font-weight: bold;
}

.btnGroup {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>